import React,{useEffect,useState,useRef} from 'react';
import {
    SafeAreaView,
    StyleSheet,
    ScrollView,
    View,
    Text,
    Image,ImageBackground,
    DeviceEventEmitter, TextInput,
} from 'react-native';
import Header from '../../widgets/Header';
import {cutZero, getffly, numAdd, numMulti, setTextThousand} from '../../utils/common';
import screen from '../../utils/screen';
import {useStores} from '../../store';
import {observer} from 'mobx-react';
import {LGBtn,OLBtn} from '../../widgets/buttons';
import RequestUtil from '../../utils/RequestUtil';
import Api from '../../utils/Api';
import {AppModal} from '../../widgets/modal';
import AppEvent from '../../utils/AppEvent';
import Constants from '../../utils/Constants';
import ShadowBoxView from '../../widgets/ShadowBoxView';
import Images from '../../images/Images';
import InvestDialog from '../../components/InvestDialog';
const cardW = screen.width - screen.PIXEL_60
const cardH = cardW * 973 / 650



export default ({navigation})=>{


    const [data,setData] = useState(null)

    const investId = navigation.state.params.id
    const investDialog = useRef()

    useEffect(()=>{
        getData()
    },[])



    const  getData = ()=>{

        AppModal.showLoading();

        let url = Api.myInvestDetail + `/${investId}`
        RequestUtil.get(url).then(res=>{
            AppModal.hideTip()
            let data = res.data
            console.log('invest detail',data)
            setData(data)

        },error=>{
            AppModal.hideTip()
            AppModal.showError(error.msg)
            console.log('invest detail error',error)
        })

    }


    const submit = ()=>{

        if(!check()) return

        AppModal.showLoading()
        let parma = {amount:amount}
        RequestUtil.post(Api.withdrawSubmit,parma,true).then(res=>{
            AppModal.showTip("Application submitted")
        },error=>{
            AppModal.hideTip()
            console.log(error)
            AppModal.showError(error.msg)
        })
    }

    const check = ()=>{
        let isEnable = false
        const regPos = /^\d+(\.\d+)?$/;
        let msg = ''
        if(!regPos.test(amount)){
            msg = Constants.error.invalid__number
            isEnable = false
        }else{
            if(data.normal.limitTimes.left <=0 ){
                msg = Constants.account.according_1 + data.normal.limitTimes.perDay + Constants.account.times_day
                isEnable = false
            }else if(Number(amount) < data.normal.min){
                msg = Constants.account.according_2 + Constants.appsymbol + setTextThousand(data.normal.min) + '.'
                isEnable = false
            }else if(Number(amount) > data.normal.max){
                msg = Constants.account.according_3 + Constants.appsymbol + setTextThousand(data.normal.max) + '.'
                isEnable = false
            }
        }
        AppModal.alert(Constants.common.note,msg,[{
            title:Constants.common.OK,
            onPress:()=>{
                AppModal.hideAlert()
            }
        }])
        return isEnable
    }

    const cancel = ()=>{
        AppModal.showLoading()
        let url = Api.investmentRedeem + `/${investId}`
        RequestUtil.post(url).then(res=>{
            console.log('cancel',res)
            AppModal.hideTip()
            AppModal.showSuccess(Constants.account.successfully_invested)
            setTimeout(()=>{
                DeviceEventEmitter.emit(AppEvent.update_account)
                DeviceEventEmitter.emit(AppEvent.invest_update)
                getData()
            },1500)

        },error=>{
            AppModal.hideTip()
            console.log(error)
            AppModal.showError(error.msg)
        })
    }


    const renderRow = (leftTitle,rightTitle)=>{
        return (
            <View style={{flexDirection:'row',justifyContent: 'space-between',alignItems:'center'}}>
                <Text style={{fontSize:13,color:'#AEAEAE' }}>{leftTitle}</Text>
                <Text style={{fontSize:13,color:'#377C74' }}>{rightTitle}</Text>
            </View>
        )
    }

    const reinvest = ()=>{
        let product = {...data.product,balance:data.balance}
        investDialog.current.show(product,()=>{
            investDialog.current.hideDialog()
            navigation.pop()
        })
    }

    const getRedemptionAmount = ()=>{

        let num1 = numMulti(data.order.amount,data.order.interest)
        let num2 = numAdd(data.order.amount,num1)
        return setTextThousand(cutZero(num2))
    }

    const renderBottomBtnContainer = ()=>{
        const status = data.order.status
        if(status === 'investing'){
            return (
                <View style={{flexDirection:'row',marginVertical:screen.PIXEL_60,paddingHorizontal:screen.PIXEL_30}}>

                    <LGBtn
                        style={{flex:1,height:screen.PIXEL_90}}
                        title={Constants.common.cancel}
                        onPress={()=>{

                            let msgTitle = Constants.account.redemption_date_1 + numMulti(data.product.redemption_fee,100) + Constants.account.redemption_date_2
                            AppModal.alert(Constants.common.note,msgTitle,[
                                {
                                    title:Constants.common.continue,
                                    onPress:()=>{
                                        AppModal.hideAlert()
                                        cancel()
                                    }
                                },{
                                    title:Constants.common.later,
                                    onPress:()=>{
                                        AppModal.hideAlert()
                                    }
                                }
                            ])
                        } }
                    />

                </View>
            )
        }else if(status === 'redeemable'){
            return  (
                <View style={{flexDirection:'row',marginVertical:screen.PIXEL_60,paddingHorizontal:screen.PIXEL_30}}>

                    <OLBtn
                        style={{flex:1,height:screen.PIXEL_90}}
                        title={Constants.account.reinvest}
                        onPress={()=> {
                            reinvest()
                        } }
                    />
                    <View style={{width:screen.PIXEL_30}}/>
                    <LGBtn
                        style={{flex:1,height:screen.PIXEL_90}}
                        title={Constants.account.redeem}
                        onPress={()=> {
                            let msgTitle = Constants.account.redeem_now_ask
                            AppModal.alert(Constants.account.redeem,msgTitle,[
                                {
                                    title:Constants.common.cancel,
                                    onPress:()=>{
                                        AppModal.hideAlert()

                                    }
                                },{
                                    title:Constants.common.continue,
                                    onPress:()=>{
                                        AppModal.hideAlert()
                                        cancel()
                                    }
                                }
                            ])
                        }}
                    />

                </View>
            )
        }else{
            return (
                <View style={{flexDirection:'row',marginVertical:screen.PIXEL_60,paddingHorizontal:screen.PIXEL_30}}>

                    <LGBtn
                        style={{flex:1,height:screen.PIXEL_90}}
                        title={Constants.account.invest_again}
                        onPress={()=> {
                            reinvest()
                        } }
                    />

                </View>
            )
        }
    }


    return (
        <View style={styles.container}>
            <Header title={Constants.account.investment_detail} navigation={navigation}/>

            {data && (
                <ScrollView
                    contentContainerStyle={{
                        paddingVertical: screen.PIXEL_20,
                        paddingHorizontal: screen.PIXEL_30,
                    }}
                >

                    <ImageBackground
                        style={{width:cardW,height:cardH,overflow:'hidden',justifyContent: 'flex-end'}}
                        resizeMode={'contain'}
                        source={Images.card_bg1}
                    >
                        <View style={[styles.tabBg,{backgroundColor: data.order.status === 'cancelled' ? '#C1C1C1' : '#FD7315'}]}>
                            <Text style={{color:'#fff',fontSize: 13}}>{data.order.status}</Text>
                        </View>
                        <View style={{height:screen.PIXEL_280 + 5,padding:screen.PIXEL_30,alignItems:'center',justifyContent: 'center'}}>
                            <Text style={{color:'#000',fontSize:13}}>{Constants.account.amount}</Text>
                            <Text style={{color:'#FF7012',fontSize:37}}>{`${Constants.appsymbol} ${setTextThousand(cutZero(data.order.amount))}`}</Text>

                            <Text style={{color:'#29B2A6',fontSize:13}}>{Constants.account.invest_in_amazon_seller_muckty}</Text>


                        </View>


                        <Image source={Images.dot_line}
                            // resizeMode={'contain'}
                               style={styles.dotLine}
                        />
                        <View style={{flex:1,padding:screen.PIXEL_30,justifyContent: 'space-between'}}>
                            {renderRow(Constants.account.interest,`${Constants.appsymbol} ${numMulti(data.order.interest,100)}%` )}
                            {renderRow(Constants.account.profit,`${Constants.appsymbol} ${setTextThousand(cutZero(data.order.profit))}` )}
                            {renderRow(Constants.account.redemption_amount,getRedemptionAmount() )}
                            {renderRow(Constants.account.cycle,`${data.order.holding_days}/${data.order.cycle}${Constants.account.days}` )}
                            {renderRow(Constants.account.start_date, data.order.start_time)}
                            {renderRow(Constants.account.redemption_date,data.order.end_time )}
                        </View>

                        {renderBottomBtnContainer()}

                    </ImageBackground>



                </ScrollView>
            )}

            <InvestDialog ref={investDialog} navigation={navigation}/>

        </View>
    )
}

const styles= StyleSheet.create({
    container:{
        flex:1,
        // backgroundColor: '#fff'
    },
    content:{
        flex:1,
        paddingHorizontal:screen.PIXEL_60,
        alignItems: 'center'
    },
    input:{
        fontFamily:getffly("bold"), height: screen.PIXEL_80, width: '100%', color: '#000',
        padding: 0, fontSize: 20,backgroundColor:'rgba(101,176,169,0.16)',
        marginTop: screen.PIXEL_20,paddingHorizontal: screen.PIXEL_20
    },
    btnGray:{
        width:'100%',height:screen.PIXEL_90,marginTop:screen.PIXEL_40,borderRadius:screen.PIXEL_90/2,
        backgroundColor:'#C1C1C1',justifyContent:'center',alignItems:'center'
    },
    dotLine:{
        marginLeft:screen.PIXEL_40,
        height:1,width:cardW - screen.PIXEL_80
    },
    tabBg:{
        position:'absolute',top:0,right:screen.PIXEL_20,height:screen.PIXEL_60,width:screen.PIXEL_180,
        backgroundColor:'#FF7012',borderBottomLeftRadius:screen.PIXEL_20,borderBottomRightRadius: screen.PIXEL_20,
        justifyContent: 'center',alignItems:'center'

    }
})
